package com.scs.application.modules.msg.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.msg.domain.PCMessage;
import com.scs.application.core.msg.domain.RawMessage;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.msg.entity.PushedRecord;
import com.scs.application.modules.msg.entity.Receive;
import com.scs.application.modules.msg.exception.SendMessageException;
import com.scs.application.modules.msg.service.ReceiveService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@AllArgsConstructor
public class SendPCMessageProvider implements SendMessageProvider<PCMessage> {

    private final ReceiveService receiveService;

    @Override
    public boolean check(PCMessage message) {
        if (StringUtils.isBlank(message.getUserLoginKey())) {
            throw new BusinessException("PC消息校验失败，登录账号不能为空");
        }
        if (StringUtils.isBlank(message.getContent())) {
            throw new BusinessException("PC消息校验失败，消息内容不能为空");
        }

        return true;
    }

    @Override
    public boolean support(Class<? extends RawMessage> clz) {
        return (PCMessage.class.isAssignableFrom(clz));
    }

    /**
     * 构建pushRecord
     *
     * @param pushedRecord
     * @param pcMessage
     * @return
     */
    @Override
    public PushedRecord getPushedRecord(PushedRecord pushedRecord, PCMessage pcMessage) {
        pushedRecord.setTitle(pcMessage.getTitle())
                .setContent(pcMessage.getContent())
                .setReceiver(pcMessage.getUserLoginKey())
                .setParams(pcMessage.getParams() != null ? JSONObject.parseObject(JSON.toJSONString(pcMessage.getParams())) : null);
        return pushedRecord;
    }

    @Override
    public void send(PCMessage pcMessage) throws SendMessageException {
        Receive receive = new Receive();

        String creator = pcMessage.getParams().get("creator") == null ? "anonymous" : pcMessage.getParams().get("creator").toString();
        receive.setIsRead("0")
                .setIsDeleted("0")
                .setContent(pcMessage.getContent())
                .setTitle(pcMessage.getTitle())
                .setReceiver(pcMessage.getUserLoginKey())
                .setGmtCreate(new Date())
                .setCreator(creator)
        ;
        receiveService.save(receive);
    }
}
